package impl;

import anaydis.sort.Sorter;
import anaydis.sort.SorterType;
import anaydis.sort.gui.ObservableSorter;
import anaydis.sort.gui.SorterListener;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

/**
 * Created by IntelliJ IDEA.
 * User: Keevu
 * Date: 17/08/11
 * Time: 15:10
 * To change this template use File | Settings | File Templates.
 */
public abstract class AbstractSorter implements Sorter, ObservableSorter {
    private SorterType sorterType;
    private List<SorterListener> listeners;

    public AbstractSorter(SorterType sorterType) {
        listeners = new ArrayList<SorterListener>();
        this.sorterType = sorterType;

    }

    public SorterType getType() {
        return sorterType;
    }

    public void addSorterListener(SorterListener s) {
        listeners.add(s);
    }

    public void removeSorterListener(SorterListener s) {
        listeners.remove(s);
    }

    protected <T> boolean greater(Comparator<T> c, List<T> list, int i, int j) {

        for (SorterListener sorterListener : listeners) {

            sorterListener.greater(i, j);

        }


        return c.compare(list.get(i), list.get(j)) > 0;

    }

    protected <T> boolean greater(Locale loc, Comparator<T> c, List<T> list, int i, int j) {

        for (SorterListener sorterListener : listeners) {

            sorterListener.greater(i, j);

        }

        Collator collator = Collator.getInstance(loc);
        return collator.compare(list.get(i), list.get(j)) > 0;

    }


    protected <T> boolean equals(Comparator<T> c, List<T> l, int i, int j) {
        for (int k = 0; k < listeners.size(); k++) {
            listeners.get(k).equals(i, j);
        }
        return c.compare(l.get(i), l.get(j)) == 0;

    }

    protected <T> void swap(List<T> list, int i, int j) {
        for (SorterListener sorterListener : listeners) {

            sorterListener.swap(i, j);

        }


        T aux = list.set(i, list.get(j));

        list.set(j, aux);


    }

}
